package cn.bitkit.component.context;

import cn.bitkit.base.annotation.BizService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;

import java.util.HashMap;
import java.util.Map;

/**
 *	服务选择器
 * @author changbo
 *
 */
@Slf4j
public class BizServiceContext extends ApplicationObjectSupport {

    private final static Map<String, Object> SERVICE_MAP = new HashMap<>(10);

    @Override
    protected void initApplicationContext(@NotNull ApplicationContext context) throws BeansException {
        super.initApplicationContext(context);
        Map<String, Object> map = context.getBeansWithAnnotation(BizService.class);
        map.values().forEach(bean -> {
            BizService[] codes = bean.getClass().getAnnotationsByType(BizService.class);
            for(BizService code : codes) {
                log.info("BizService:{}", code.value());
                SERVICE_MAP.put(code.value(), bean);
            }
        });
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBizService(String code) {
        return (T) SERVICE_MAP.get(code);
    }

}
